package top.soulblack.purchasesale.controller.setting;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import top.soulblack.purchasesale.common.Result;
import top.soulblack.purchasesale.service.BarCodeService;

import static top.soulblack.purchasesale.common.CodeMsg.*;

@Controller
@RequestMapping("/barcode")
public class BarcodeController {
    @Autowired
    private BarCodeService barcodeService;

    @RequestMapping("/savebarcode")
    @ResponseBody
    public Result<Boolean> savebarcode(boolean _static, int factory, int start, int barcodeItem) {
        if(factory==0)
            return Result.error(BAECODE_EXIST);
        String factoryCode= String.format("%08d", factory);
        String startCode= String.format("%04d", start);
        String code = factoryCode + startCode;
        if (code.length()!=12)
            return Result.error(BAECODE_EXIST);
        int a = 0, b = 0, c = 0, d = 0;
        for (int i = 0; i < 12; i += 2) {
            a += (code.charAt(i) - '0');
            b += (code.charAt(i + 1) - '0');
        }
        c = (a + b * 3) % 10;
        d = (10 - c) % 10;
        startCode=startCode+d;
        if(barcodeItem==1){
            barcodeService.setproduct(_static,factoryCode,startCode,barcodeItem);
            return Result.success(true);
        }
        if(barcodeItem==2){
            barcodeService.setsingle(_static,factoryCode,startCode,barcodeItem);
            return Result.success(true);
        }
        return Result.error(BAECODE_SAVE_ERROR);
    }

    @RequestMapping("/generate")
    @ResponseBody
    // 后期需要加上User权限验证，否则暴露接口有危险。
    public String generate(int barcodeItem) {
        String a=barcodeService.generate(barcodeItem);
        return a;
    }
}